﻿/***********************
Author:莫可
Copyright:Ehai工作室
CreateDate:2009-7-28
AlterTime:2009-8-1
Version:1.1
***********************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Text.RegularExpressions;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Security.Cryptography;
using Ehai.Web.Framework;

namespace Ehai.Web.Framework.Rules
{
    class LoginRuleHandle: IMsgRuleHandle
    {
        #region IMsgRuleHandle 成员

#if DEBUG
        private int _execStatus = 0;
        public int ExecStatus
        {
            get { return _execStatus; }
        }
#endif
        public const string Name = "login";
        public string MD5(string strPwd)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] data = System.Text.Encoding.Default.GetBytes(strPwd);//将字符编码为一个字节序列
            byte[] md5data = md5.ComputeHash(data);//计算data字节数组的哈希值
            md5.Clear();
            string str = "";
            for (int i = 0; i < md5data.Length - 1; i++)
            {
                str += md5data[i].ToString("x").PadLeft(2, '0');
            }
            return str;
        }
        /// <summary>
        /// 登陆操作
        /// </summary>
        /// <param name="p">
        ///0:(必选)处理类型,即"login"<br/>
        ///1:(必选)用户名.<br/>
        ///2:(必选)密码.<br/> 
        ///3:(可选)用户表名.如果为null,默认使用EhaiAMS数据库中ComnUser表<br/>
        ///4:(可选)登陆日志表名.如果为null,默认使用EhaiAMS数据库中的log表.<br/>
        ///5:(可选)数据库连接字符串.参考:configuration.config中的conn节点下的值.如果为null,默认使用"id1".<br/>
        ///6:(可选)验证码.如果为null,则不进行验证码判断操作.<br/>
        ///</param>
        ///<param name="ci">环境变量</param>
        ///<example>
        ///string[] p = { "login", "moke", "111111", "ComnUser", "log","","id1" };
        ///string[0][0] strArr ="101"
        /// </example>
        ///<exception cref="Ehai.Web.Framework.WebException">
        ///Ehai.Web.Framework.WebException:登陆错误<br/>
        ///</exception>
        /// <returns>状态值，包含在strArr[0][0]</returns>
        public string[][] Execute(string[] p, ContextInfo ci)
        {
#if DEBUG
            if (p.Length > 7 || p.Length < 3)
            {
                _execStatus = -2;
                return null;
            }
            if (p[0].Trim() == String.Empty || p[1].Trim() == String.Empty || p[2].Trim() == string.Empty)
            {
                if (p[0].Trim() == String.Empty)
                    _execStatus = 1;
                if (p[1].Trim() == String.Empty)
                    _execStatus = 2;
                if (p[2].Trim() == String.Empty)
                    _execStatus = 3;
                return null;
            }

#endif

#if DEBUG
            //测试时的假数据,使用时去除注释标记,实际使用时由产生Session["code"]的界面产生
            ci.Session["code"] = "AAAA";
#endif

            //定义及初始化字符串数组用以返回信息
            string[][] strArr;
            strArr = new string[1][] { new string[] { String.Empty, String.Empty } };

            string userName = p[1].Trim();
            string password = p[2].Trim();

            if (!(Validator.IsNickName(userName, 20) && Validator.IsPassword(password, 4, 20)))
            {
#if DEBUG
                _execStatus = 0;
#endif
                strArr[0][0] = "101";
                return strArr;
            }
            string pwdEncrypt = MD5(password);//使用MD5方法给密码加密

            string userTable = p.Length > 3 ? p[3].Trim() : "ComnUser";
            if (userTable.Trim() == string.Empty) { userTable = "ComnUser"; }

            string logTable = p.Length > 4 ? p[4].Trim() : "log";
            if (logTable.Trim() == string.Empty) { logTable = "log"; }

            string conn = p.Length > 5 ? p[5].Trim() : "id1";
            if (conn.Trim() == string.Empty) { conn = "id1"; }

            string LoginCode = p.Length > 6 ? p[6].Trim() : null;

            string PassKey = "0";

            if (LoginCode == null)
            {
                PassKey = "1";
            }
            else
            {
                string session = ci.Session["code"].ToString();
                string UpperCase = LoginCode.ToUpper();//把用户输入的验证码字符进行大小写忽略的处理
                if (UpperCase == session)
                {
                    PassKey = "1";
                }
                else
                {
#if DEBUG
                _execStatus = 0;
#endif
                    strArr[0][0] = "102";
                    return strArr;
                }
            }

            try
            {
                if (PassKey == "1")
                {
                    string sql = "select UserName, password from " + userTable + " where UserName = \'" + userName + "\'and password=\'" + pwdEncrypt + "\'";
                    ApplicationDB ad = new ApplicationDB(sql, ci, conn);
                    DataSet ds = ad.GetDataSet();
                    if (ds.Tables[0].Rows.Count == 0)
                    {
#if DEBUG
                _execStatus = 0;
#endif
                        strArr[0][0] = "103";
                        return strArr;
                    }
                    else
                    {

                        HttpBrowserCapabilities bc = HttpContext.Current.Request.Browser;//定义一个浏览器对象
                        DateTime now = DateTime.Now;
                        string ReplacedSQL = sql.Replace("'", "#");
                        ApplicationDB adlog = new ApplicationDB("insert into " + logTable + "(msg,username,browserName,browserVersion,browserPlatform,IP,operationTime) values(\'" + ReplacedSQL + "\',\'" + userName + "\',\'" + bc.Browser + "\',\'" + bc.Version + "\',\'" + bc.Platform + "\',\'" + HttpContext.Current.Request.UserHostAddress + "\',\'" + now + "\')", ci, conn);
                        adlog.ExecuteNonQuery();
#if DEBUG
                _execStatus = 0;
#endif
                        strArr[0][0] = "201";
                        return strArr;
                    }
                }
                else
                {
#if DEBUG
                _execStatus = 0;
#endif
                    strArr[0][0] = "104";
                    return strArr;
                }
            }

            catch (Exception ex)
            {
#if DEBUG
                _execStatus = -1;
#endif
                throw new Ehai.Web.Framework.WebException("Ehai.Web.LoginRules", "登陆错误！", ex);
            }
        }

        public string GetHelpInfo()
        {
            return "进行登录操作,必选参数共3个,分别是login,用户名,密码,可选参数请参考GetParametersInfo";
        }

        public string GetHelpDetail()
        {
            return "例1:{ \"login\", \"moke\", \"111111\", \"ComnUser\", \"log\",\"id1\",\"xxxx\" };<br/>101:登陆请求字符格式有误，未通过后台验证.<br/>102:前台验证码错误,请检查!<br/>103:用户名或密码错误,请检查!<br/>104:系统错误，请联系管理员!<br/>201:登陆成功!";
            
        }

        public string[] GetParametersInfo()
        {
            string[] t = new string [7];
            t[0] = "(必选)处理类型,即\"login\"";
            t[1] = "(必选)用户名.";
            t[2] = "(必选)密码.";
            t[3] = "(可选)用户表名.如果为null,默认使用EhaiAMS数据库中ComnUser表.";
            t[4] = "(可选)登陆日志表名.如果为null,默认使用EhaiAMS数据库中的log表.";
            t[5] = "(可选)数据库连接字符串.参考:configuration.config中的conn节点下的值.如果为null,默认使用\"id1\".";
            t[6] = "(可选)验证码.如果为null,则不进行验证码判断操作.";
            return t;
        }

        #endregion
    }
}
